using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace SynoManager.DownloadStation
{
    public class OpenDownloadFileDialog : Component
    {
        private readonly DownloadStationService service;
        private OpenFileDialog dialog = new OpenFileDialog();
        private IDownloadFileHandlerPlugin[] handlers;

        internal OpenDownloadFileDialog(DownloadStationService service)
        {
            this.service = service;
            var manager = service.Plugins;
            dialog.Title = "Open Download file";

            StringBuilder sb = new StringBuilder();
            List<string> extensions = new List<string>();
            handlers = new IDownloadFileHandlerPlugin[manager.FileHandlers.Count()];
            int index = 0;
            foreach(var plugin in manager.FileHandlers)
            {
                string ext = plugin.Filter;
                if (plugin.IncludeInAllFiles && !extensions.Contains(ext))
                {
                    extensions.Add(ext);
                }

                handlers[index++] = plugin;

                sb.Append(plugin.FileTypeDescription + "|" + ext + "|");
            }

            string[] values = extensions.ToArray();
            sb.Insert(0, "All Downloadable Files (" + String.Join(";", values) + ")|"+String.Join(";", values)+"|");
            sb.Append("All Files (*.*)|*.*");

            dialog.Filter = sb.ToString();
        }

        public DialogResult ShowDialog(IWin32Window owner)
        {
            return dialog.ShowDialog(owner);
        }

        public DialogResult ShowDialog()
        {
            return dialog.ShowDialog();
        }

        public string FileName
        {
            get { return dialog.FileName; }
        }

        public string[] Filenames
        {
            get
            {
                return dialog.FileNames;
            }
        }

        public DialogResult Execute(IWin32Window owner)
        {
            DialogResult result = ShowDialog(owner);
            if (DialogResult.OK == result)
            {
                ProcessSelected();
            }
            return result;
        }

        public void ProcessSelected()
        {
            if ((dialog.FilterIndex > 1) && (dialog.FilterIndex <= handlers.Length))
            {
                foreach (string path in Filenames)
                    handlers[dialog.FilterIndex].CreateTask(path);
            }
            else
            {
                foreach(string path in Filenames)
                    service.AddFile(path);
            }
        }
    }
}